package com.scalar.chiptrack.adaptor.beceem;

import com.scalar.chiptrack.jobs.JobHandler;

import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.CSVParserImpl;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.AssemblyLot;
import com.scalar.chiptrack.adaptor.TestLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AssemblyAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.TestAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;

import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import java.io.File;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;


/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 9 Apr, 2010
 * Time: 12:02:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class StatsDataParser extends JobHandler implements AdaptorConstants
{
    private HashMap<String, FabSortLot> m_sortDataMap       = new HashMap<String, FabSortLot>();
    private HashMap<String, InventoryLot> m_dieBankDataMap	= new HashMap<String, InventoryLot>();
    private HashMap<String, AssemblyLot> m_assyDataMap      = new HashMap<String, AssemblyLot>();
    private HashMap<String, TestLot> m_ftDataMap            = new HashMap<String, TestLot>();
    private HashMap<String, InventoryLot> m_fgDataMap       = new HashMap<String, InventoryLot>();
	private HashMap<String, InventoryLot> m_waferStoreDataMap    = new HashMap<String, InventoryLot>();
	private HashMap<String, ShippedLot> m_assyShipDataMap   = new HashMap<String, ShippedLot>();
	private HashMap<String, ShippedLot> m_ftShipDataMap     = new HashMap<String, ShippedLot>();

    private Logger m_parserLogger   = null;
    private String m_dataOutputDir  = null;

    public StatsDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir(VENDOR_NAME_SCK, WIP_TYPE_ASSEMBLY);
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_SCK );
            AssemblyAdaptorDAO.setLogger( m_parserLogger );
            TestAdaptorDAO.setLogger( m_parserLogger );
            InventoryLotDAO.setLogger(m_parserLogger);
            ShippedLotDAO.setLogger( m_parserLogger );
            FabSortAdaptorDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger( m_parserLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading STATS WIP output directory details from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new StatsDataParser().execute();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader( "STATS ", CONSTANT_PARSER);

        File doneDestDir = new File(  m_dataOutputDir + "/done" );

        File sourceDataoutDir = new File( m_dataOutputDir );

        File[] fileList = sourceDataoutDir.listFiles();
        if ( ( fileList == null ) || ( fileList.length <= 3 ) )
        {
            log( "No file found in directory: " + sourceDataoutDir );
            throw new ScalarException( "\n+-----------No file found in directory " + sourceDataoutDir );
        }

        ArrayList<File> successFileList = new ArrayList<File>();

        boolean success = false;

        for ( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() == true )
            {
                continue;
            }

            try
            {
                // Step 1
                // Parse Files to get Object List
                if ( fileList[i].getName() != null && fileList[i].getName().trim().startsWith( StatsFTPAdaptor.FILE_NAME_WIP ) )
                {
                    parseAllWipReport( fileList[i].getAbsolutePath() );

                    successFileList.add( fileList[i] );
                }

                success = true;
            }
            catch ( Exception e )
            {
                success = false;
                log( "Exception while parsing and storing file: " + fileList[i].getAbsolutePath() + "\nException: " + e );
                e.printStackTrace();
                throw e;
            }
        }
        /*Updating the Wafer Store Lot Information*/
        try
        {
            // Save Wafer Store Information
            if (m_waferStoreDataMap.isEmpty() == false)
            {
                log(" Updating Wafer Store Lot Information");
                InventoryLotDAO.saveInventoryLot(null, m_waferStoreDataMap.values().iterator(), LOCATION_TYPE_WAFER_BANK, null);
            }
            else
            {
                InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_WAFER_BANK, null );
            }
            success = true;
            m_waferStoreDataMap.clear();
            m_waferStoreDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Wafer Store Lot information into database: " + se);
            throw se;
        }

        //to saving sort Lot Info
        try
        {
            // Save Sort Information
            if ( m_sortDataMap.isEmpty() == false )
            {
                log( " Updating Sort Lot Information" );
                FabSortAdaptorDAO.saveSortLot( null, m_sortDataMap.values().iterator(), WIP_TYPE_SORT, null );
            }
            else
            {
                FabSortAdaptorDAO.closeSortLot( null, WIP_TYPE_SORT, null );
            }
            success = true;
            m_sortDataMap.clear();
            m_sortDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Sort Lot information into database: " + se );
            throw se;
        }

        /*Updating the Die Bank Lot Information*/
        try
        {
            // Save Die Bank Information
            if (m_dieBankDataMap.isEmpty() == false)
            {
                log(" Updating Die Bank Lot Information");
                InventoryLotDAO.saveInventoryLot(null, m_dieBankDataMap.values().iterator(), LOCATION_TYPE_DIE_BANK, VENDOR_NAME_SCK);
            }
            else
            {
                InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_DIE_BANK, VENDOR_NAME_SCK);
            }
            success = true;
            m_dieBankDataMap.clear();
            m_dieBankDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Die Bank Lot information into database: " + se);
            throw se;
        }

        /*Assembly Lot Saving*/
        try
        {
            // Save Assembly Information
            if ( m_assyDataMap.isEmpty() == false )
            {
                log( " Updating Assembly Lot Information" );
                AssemblyAdaptorDAO.saveAssemblyLot( null, m_assyDataMap.values().iterator(), WIP_TYPE_ASSEMBLY, VENDOR_NAME_SCK );
            }
            else
            {
                AssemblyAdaptorDAO.closeAssemblyLot( null, WIP_TYPE_ASSEMBLY, VENDOR_NAME_SCK);
            }
            success = true;
            m_assyDataMap.clear();
            m_assyDataMap = null;

        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update SCS/SCK Assembly Lot information into database: " + se );
            throw se;
        }

        try
        {
            // Save Assembly Ship Information
            if ( m_assyShipDataMap.isEmpty() == false )
            {
                log( " Updating Assembly Shiping Lot Information" );
                ShippedLotDAO.saveShippedLot( null, m_assyShipDataMap.values().iterator() );
            }
            success = true;
            m_assyShipDataMap.clear();
            m_assyShipDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Assembly Shipping Lot information into database: " + se );
            throw se;
        }

        // Saving the Test Lot Information
        try
        {
            // Save Final Test Information
            if ( m_ftDataMap.isEmpty() == false )
            {
                log( " Updating Test Lot Information" );
                TestAdaptorDAO.saveTestLot( null, m_ftDataMap.values().iterator(), LOCATION_TYPE_FT, VENDOR_NAME_SCK );
            }
            else
            {
                TestAdaptorDAO.closeTestLot( null, LOCATION_TYPE_FT, VENDOR_NAME_SCK );
            }

            success = true;
            m_ftDataMap.clear();
            m_ftDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Test Lot information into database: " + se );
            throw se;
        }

        try
        {
            // Save FT Ship Information
            if ( m_ftShipDataMap.isEmpty() == false )
            {
                log( " Updating FT Shiping Lot Information" );
                ShippedLotDAO.saveShippedLot( null, m_ftShipDataMap.values().iterator() );
            }
            success = true;
            m_ftShipDataMap.clear();
            m_ftShipDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update FT Shipping Lot information into database: " + se );
            throw se;
        }


	   // to save the FG lot tables
       try
       {   //FG Only for SCS Vendor
           if ( m_fgDataMap.isEmpty() == false )
           {
               log(" Updating Finshed Goods Lot Information");
               InventoryLotDAO.saveInventoryLot(null, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_SCK );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_SCK  );
           }
       }
       catch (ScalarException se)
       {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Finshed Goods Lot information into database: " + se);
          throw se;
       }

       // To Close the Drop Out Lots
       AdaptorDAO.closeDropOutLots(VENDOR_NAME_SCS);
       AdaptorDAO.closeDropOutLots(VENDOR_NAME_SCK);

      // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
      AdaptorDAO.sendAllNotifications(VENDOR_NAME_SCS, true, true, true);
      AdaptorDAO.sendAllNotifications(VENDOR_NAME_SCK, true, true, true);

       int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( StatsFTPAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, StatsFTPAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, StatsFTPAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
    }

    /**
     *
     * @param fileName
     * @throws Exception
     */
    private void parseAllWipReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result            = null;
        TestLot testLot         = null;
        InventoryLot inventoryLot = null;
        AssemblyLot  assemblyLot  = null;
        FabSortLot fabSortLot     = null;
        String lotNumber        = null;
        String partNumber       = null;
        String fablotNumber     = null;
        String vendor			= null;

        try
        {
            File fabWipFile = new File( fileName );
            if ( fabWipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Wip Report..." );
            Parser parser = ParserFactory.getCSVParser( fabWipFile, ',' );

            ((CSVParserImpl)parser).setHeaderRowIdx(0);
            ((CSVParserImpl)parser).setDataStartRowIdx(1);

            result = parser.parse();

            while (result.next())
            {
                fablotNumber    = result.getString("Wafer Lotid");
                partNumber      = result.getString("Customer Device");
                lotNumber       = result.getString("Customer Lot Number");

                if( result.getString("Plant") != null && result.getString("Plant").equalsIgnoreCase( "SCS" ) )
                {
                	vendor = VENDOR_NAME_SCS;
                }
                else if ( result.getString("Plant") != null &&  result.getString("Plant").equalsIgnoreCase( "SCK" ) )
                {
                	vendor = VENDOR_NAME_SCK;
                }
                                
                if( lotNumber == null )
                {
                    lotNumber = fablotNumber;
                }

                String lotStatus = null;
                String lotCategory = null;
                if( result.getString("State") != null && ( "WAIT".equalsIgnoreCase( result.getString("State") )
                        || "HELD".equalsIgnoreCase( result.getString("State") ) || result.getString("State").indexOf("HLD") != -1 ) )
                {
                    lotStatus = LOT_STATUS_HOLD;
                }
                else
                {
                    lotStatus = LOT_STATUS_RUNNING;
                }
                if ( "ENG".equalsIgnoreCase( result.getString("LotType") ) || "QUAL".equalsIgnoreCase(result.getString("LotType"))
                                || "EG".equalsIgnoreCase( result.getString("LotType") ) || "QL".equalsIgnoreCase(result.getString("LotType")) )
                {
                    lotCategory = LOT_CATEGORY_TYPE_ENGG;
                }
                else
                {
                    lotCategory = LOT_CATEGORY_TYPE_PROD;
                }
                String dateIn = null;
                String expectedDateOut = null;
                if ( result.getString("Stateentrytime") != null )
                {
                     dateIn = StringUtils.formatDate(result.getString("Stateentrytime"),"dd-MMM-yy", "MM/dd/yyyy" );
                }
                else if ( result.getString("Stagestarttime") != null )
                {
                     dateIn = StringUtils.formatDate(result.getString("Stagestarttime"),"dd-MMM-yy", "MM/dd/yyyy" );
                }
                else if ( result.getString("Sm Createtime") != null )
                {
                     dateIn = StringUtils.formatDate(result.getString("Sm Createtime"),"dd-MMM-yy", "MM/dd/yyyy" );
                }
                else
                {
                    dateIn = StringUtils.formatDateToString( new Date() );
                }

                if ( result.getString("CRD") != null )
                {
                     expectedDateOut = StringUtils.formatDate(result.getString("CRD"),"dd-MMM-yy", "MM/dd/yyyy" );
                }
                else if ( result.getString("CSD") != null )
                {
                     expectedDateOut = StringUtils.formatDate(result.getString("CSD"),"dd-MMM-yy", "MM/dd/yyyy" );
                }
                else if ( result.getString("OSD") != null )
                {
                     expectedDateOut = StringUtils.formatDate(result.getString("OSD"),"dd-MMM-yy", "MM/dd/yyyy" );
                }

                if ( lotNumber != null && lotNumber.trim().length() > 0 && partNumber != null && partNumber.trim().length() > 0)
                {
                    //SORT
                    if (result.getString("Production Area") != null && "W".equalsIgnoreCase( result.getString("(D)ie/(W)afer"))
                            && ( "TEST".equalsIgnoreCase( result.getString("Production Area") ) || "FG".equalsIgnoreCase( result.getString("Production Area") ) 
						          || "FGS".equalsIgnoreCase( result.getString("Production Area") )  ) )
                    {

                        fabSortLot = m_sortDataMap.get(partNumber + fablotNumber );

                        if ( fabSortLot == null )
                        {
                            fabSortLot = new FabSortLot( vendor, WIP_TYPE_SORT);
                            m_sortDataMap.put( partNumber+ fablotNumber, fabSortLot);
                        }
                        int wquantity =0;
                        if (fabSortLot.getQtyIn() != null)
                        {
                            try
                            {
                                wquantity = Integer.parseInt(fabSortLot.getQtyIn());
                            }
                            catch (NumberFormatException ignore) {
                            }
                            wquantity += result.getInt("Current Wafer Qty SUM");
                        }
                        else
                        {
                            wquantity = result.getInt("Current Wafer Qty SUM");
                        }
                        if (wquantity > 0 && wquantity < 26 )
                        {
                            fabSortLot.setQtyIn( wquantity+"" );
                            fabSortLot.setLotId( fablotNumber );
                            fabSortLot.setCustProduct( partNumber );
                            fabSortLot.setLotStatus( lotStatus);
                            fabSortLot.setFabLotNumber( fablotNumber );
                            fabSortLot.setPsType( LOCATION_TYPE_SORT );
                            fabSortLot.setStage( result.getString("Stage Description") );
                            fabSortLot.setLotCategory( lotCategory );
                            fabSortLot.setDateIn( dateIn );
                            fabSortLot.setPoNumber( result.getString("PO Number") );
                            fabSortLot.setForcastedDateOut( expectedDateOut );
                        }
                    }
                    //SCK SORT
                    /*if (result.getString("Production Area") != null && "WFRS".equalsIgnoreCase( result.getString("Package"))
                            && ( "TEST".equalsIgnoreCase( result.getString("Production Area") ) || "FGS".equalsIgnoreCase( result.getString("Production Area") ) ) )
                    {
                        fabSortLot = m_sortDataMap.get(partNumber + fablotNumber );

                        if ( fabSortLot == null )
                        {
                            fabSortLot = new FabSortLot( vendor, WIP_TYPE_SORT);
                            m_sortDataMap.put( partNumber+ fablotNumber, fabSortLot);
                        }
                                                
                        int wquantity =0;
                        if (fabSortLot.getQtyIn() != null)
                        {
                            try
                            {
                                wquantity = Integer.parseInt(fabSortLot.getQtyIn());
                            }
                            catch (NumberFormatException ignore) {
                            }

                            wquantity += result.getInt("Current Wafer Qty SUM");
                        }
                        else
                        {
                            wquantity = result.getInt("Current Wafer Qty SUM");
                        }
                        if (wquantity > 0 && wquantity < 26 )
                        {
                            fabSortLot.setQtyIn( wquantity+"" );
                            fabSortLot.setLotId( fablotNumber );
                            fabSortLot.setCustProduct( partNumber );
                            fabSortLot.setLotStatus( lotStatus);
                            fabSortLot.setFabLotNumber( fablotNumber );
                            fabSortLot.setPsType( LOCATION_TYPE_SORT );
                            fabSortLot.setStage( result.getString("Stage Description") );
                            fabSortLot.setLotCategory( lotCategory );
                            fabSortLot.setDateIn( dateIn );
                            fabSortLot.setPoNumber( result.getString("PO Number") );
                            fabSortLot.setForcastedDateOut( expectedDateOut );
                        }
                    } */
                    //WAFER STORE
                    if (result.getString("Production Area") != null && ( "VWAREHOUSE".equalsIgnoreCase( result.getString("Production Area") )
                            ||  "WFRPROCESS".equalsIgnoreCase( result.getString("Production Area") ) ) )
                    {

                        inventoryLot = (InventoryLot)m_waferStoreDataMap.get( partNumber + fablotNumber );

                        if ( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot( vendor, LOCATION_TYPE_WAFER_STORE );
                            m_waferStoreDataMap.put( partNumber + fablotNumber, inventoryLot );
                        }

                        int wquantity =0;
                        if (inventoryLot.getWaferQtyIn() != null)
                        {
                            try
                            {
                                wquantity = Integer.parseInt(inventoryLot.getWaferQtyIn());
                            }
                            catch (NumberFormatException ignore) {
                            }
                            wquantity += result.getInt("Current Wafer Qty SUM");
                        }
                        else
                        {
                            wquantity = result.getInt("Current Wafer Qty SUM");
                        }
                        if (wquantity > 0 )
                        {
                            inventoryLot.setPartNumber( partNumber );
                            inventoryLot.setLotNumber( fablotNumber );
                            inventoryLot.setWaferQtyIn(wquantity + "");
                            inventoryLot.setDateIn( dateIn );
                            inventoryLot.setFabLotNumber( fablotNumber );
                            inventoryLot.setLeadCount( result.getString("Leadcount") );
                            inventoryLot.setStatus( lotStatus );
                            inventoryLot.setLotCategory( lotCategory );
                            inventoryLot.setDateCode(result.getString("Datecode"));
                        }
                    }
                    //DIE BANK
                    if (result.getString("Production Area") != null && ( "Die-Bank".equalsIgnoreCase( result.getString("Production Area") ) || "DieBank".equalsIgnoreCase( result.getString("Production Area")) ) )
                    {                           
                        inventoryLot = (InventoryLot)m_dieBankDataMap.get( partNumber + fablotNumber );

                        if ( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot( vendor, LOCATION_TYPE_DIE_BANK );
                            m_dieBankDataMap.put( partNumber + fablotNumber, inventoryLot );
                        }

                        int quantity = 0;
                        int wquantity = 0;
                        if (inventoryLot.getQtyIn() != null)
                        {
                            try
                            {
                                quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                wquantity = Integer.parseInt(inventoryLot.getWaferQtyIn());
                            }
                            catch (NumberFormatException ignore) {
                            }
                            quantity += result.getInt("Current Die Qty SUM");
                            wquantity += result.getInt("Current Wafer Qty SUM");
                        }
                        else
                        {
                            quantity = result.getInt("Current Die Qty SUM");
                            wquantity = result.getInt("Current Wafer Qty SUM");
                        }

                        if (quantity > 0 )
                        {
                            inventoryLot.setPartNumber( partNumber );
                            inventoryLot.setLotNumber( fablotNumber );
                            inventoryLot.setQtyIn(quantity + "");
                            inventoryLot.setWaferQtyIn( wquantity + "");
                            inventoryLot.setDateIn( dateIn );
                            inventoryLot.setFabLotNumber( fablotNumber );
                            inventoryLot.setPkgType( result.getString("Package") );
                            inventoryLot.setLeadCount( result.getString("Leadcount") );
                            inventoryLot.setStatus( lotStatus );
                            inventoryLot.setLotCategory( lotCategory );
                            inventoryLot.setDateCode( result.getString("Datecode") );
                        }
                    }
                                        
                    //SCK ASSEMBLY
                    if (  result.getString("Production Area") != null && "ASSY".equalsIgnoreCase( result.getString("Production Area") )  )
                    {
                        assemblyLot = (AssemblyLot) m_assyDataMap.get( partNumber + lotNumber + fablotNumber );
                        if (assemblyLot == null)
                        {
                            assemblyLot = new AssemblyLot( vendor, WIP_TYPE_ASSEMBLY );
                            m_assyDataMap.put( partNumber + lotNumber + fablotNumber, assemblyLot);
                        }
                        int quantity = 0;
                        if (assemblyLot.getQtyIn() != null)
                        {
                            try
                            {
                                quantity = Integer.parseInt(assemblyLot.getQtyIn());
                            }
                            catch (NumberFormatException ignore) {
                            }
                            quantity += result.getInt("Current Die Qty SUM");
                        }
                        else
                        {
                            quantity = result.getInt("Current Die Qty SUM");
                        }
                        
                        if ( quantity > 0 )
                        {
                            assemblyLot.setLotNumber( lotNumber );
                            assemblyLot.setDeviceName( partNumber );
                            assemblyLot.setStatus(lotStatus);
                            assemblyLot.setHoldReason( result.getString("Holdreason") );
                            assemblyLot.setHoldCode( result.getString("Holdcode") );
                            assemblyLot.setPONumber(  result.getString("PO Number") );
                            assemblyLot.setFabLotNumber( fablotNumber );
                            assemblyLot.setPackageType( result.getString("Package") );
                            assemblyLot.setCategory( lotCategory );
                            assemblyLot.setLeadCount( result.getString("Leadcount") );
                            assemblyLot.setDateIn( dateIn );
                            assemblyLot.setExpectedDateOut( expectedDateOut );
                            assemblyLot.setStage( result.getString("Stage Description") );
                            assemblyLot.setQtyIn( quantity+"" );
                            assemblyLot.setDateCode( result.getString("Datecode"));
                        }
                    }

                    // FT Process

                   if ( result.getString("Production Area") != null && !"WFRS".equalsIgnoreCase( result.getString("Package"))
                           && !"W".equalsIgnoreCase( result.getString("(D)ie/(W)afer")) && ( "TEST".equalsIgnoreCase( result.getString("Production Area") ) || "POST-TEST".equalsIgnoreCase( result.getString("Production Area") ) ) )
                    {
                        testLot = (TestLot) m_ftDataMap.get( partNumber + lotNumber + fablotNumber );
                        if (testLot == null)
                        {
                            testLot = new TestLot( vendor, LOCATION_TYPE_FT );
                            m_ftDataMap.put(partNumber + lotNumber + fablotNumber, testLot);
                        }

                        int quantity = 0;
                        if (testLot.getQtyIn() != null)
                        {
                            try
                            {
                                quantity = Integer.parseInt(testLot.getQtyIn());
                            }
                            catch (NumberFormatException ignore) {
                            }
                            quantity += result.getInt("Current Die Qty SUM");
                        }
                        else
                        {
                            quantity = result.getInt("Current Die Qty SUM");
                        }

                        if ( quantity > 0 )
                        {
                            testLot.setPartNumber( partNumber );
                            testLot.setLotNumber( lotNumber );
                            testLot.setFabLotNumber( fablotNumber );
                            testLot.setDateIn( dateIn );
                            testLot.setExpecetedDate( expectedDateOut );
                            testLot.setStage( result.getString("Stage Description") );
                            testLot.setQtyIn( quantity + "");
                            testLot.setLeadCount( result.getString("Leadcount") );
                            testLot.setPackageType( result.getString("Package") );
                            testLot.setStatus(lotStatus);
                            testLot.setPoNumber(  result.getString("PO Number") );
                            testLot.setHoldReason( result.getString("Holdreason") );
                            testLot.setHoldCode( result.getString("Holdcode") );
                            testLot.setCategory( lotCategory );
                            testLot.setDateCode( result.getString("Datecode") );
                        }
                    }

                    // FG Process
                    if ( result.getString("Production Area") != null && !"WFRS".equalsIgnoreCase( result.getString("Package")) && "FGS".equalsIgnoreCase( result.getString("Production Area") ) )
                    {
                        //log(lotNumber + "In EOL");

                        inventoryLot = (InventoryLot) m_fgDataMap.get( partNumber + lotNumber + fablotNumber );
                        if (inventoryLot == null)
                        {
                            inventoryLot = new InventoryLot( vendor, LOCATION_TYPE_FG);
                            m_fgDataMap.put(partNumber + lotNumber + fablotNumber, inventoryLot);
                        }

                       int quantity = 0;
                        if (inventoryLot.getQtyIn() != null)
                        {
                            try
                            {
                                quantity = Integer.parseInt(inventoryLot.getQtyIn());
                            }
                            catch (NumberFormatException ignore) {
                            }
                            quantity += result.getInt("Current Die Qty SUM");
                        }
                        else
                        {
                            quantity = result.getInt("Current Die Qty SUM");
                        }
                        if ( quantity > 0 )
                        {
                            inventoryLot.setPartNumber( partNumber );
                            inventoryLot.setLotNumber( lotNumber );
                            inventoryLot.setFabLotNumber( fablotNumber );
                            inventoryLot.setDateIn( dateIn );
                            inventoryLot.setExpectedDate( expectedDateOut );
                            inventoryLot.setStage( result.getString("Stage Description"));
                            inventoryLot.setQtyIn(quantity+"");
                            inventoryLot.setLeadCount( result.getString("Leadcount") );
                            inventoryLot.setPkgType( result.getString("Package") );
                            inventoryLot.setStatus(lotStatus);
                            inventoryLot.setHoldReason( result.getString("Holdreason") );
                            inventoryLot.setHoldCode( result.getString("Holdcode") );
                            inventoryLot.setCategory( lotCategory );
                            inventoryLot.setDateCode( result.getString("Datecode") );
                        }
                    }
                }
            }
        }
        catch( Exception e)
        {
            System.out.println(" !!ERROR !! ERROR Exception while get getting the STATS Wip Details");
            e.printStackTrace();
            throw e;
        }
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            m_parserLogger.logDebug( message + LINE_SEPARATOR );
        }
        else
        {
            System.out.println( message );
        }
    } // end of log method
}

